#include "serialop.h"

SerialOp::SerialOp(QSerialPort* serial_ptr, QObject *parent):
    QObject(parent),
    serail_ptr_(serial_ptr)
{
    serail_ptr_ = nullptr;
}

SerialOp::~SerialOp()
{
    if (serail_ptr_) {
        if (serail_ptr_->isOpen()) {
            serail_ptr_->close();
        }
        delete serail_ptr_;
        serail_ptr_ = nullptr;
    }
}

void SerialOp::recv_data()
{
    if (serail_ptr_ != nullptr) {
        qDebug() << "recvdata" << QThread::currentThread();
        serail_op_mtx_.lock();
        QByteArray data = serail_ptr_->readAll();
        serail_op_mtx_.unlock();

        // 判断最后个字符是'\n'
        if (data.endsWith('\n')) {
            QDateTime current_time = QDateTime::currentDateTime();
            // 判断buffer是否为空
            if (!buffer.isEmpty()) {
                buffer.append(data);
                qDebug() << current_time.toString("yyyy-MM-dd hh:mm:ss.zzz") << buffer;
                // 发送信号显示串口信息
                emit uartDataTextShow(buffer);
                buffer.clear();
            } else {
                qDebug() << current_time.toString("yyyy-MM-dd hh:mm:ss.zzz") << data;
                // 发送信号显示串口信息
                emit uartDataTextShow(data);
            }
        } else {
            buffer.append(data);
        }
    }
}

void SerialOp::serail_recv_start()
{
    // 默认设置
    serail_work_thread_.start();
}

void SerialOp::setDefaultParms()
{
    static int i = 0;
    QString str_val;
    QByteArray data;

    if (serail_ptr_) {
        qDebug() << "sendthread" << QThread::currentThread();
        if (i == 0) {
            // 设置TEST_MODE
            str_val =  QString::fromUtf8(TEST_MODE) + "1\r\n";
            data = str_val.toLatin1();
            serail_send_start(data);
        } else if (i == 1) {
            // 设置RMAX默认为6
            str_val = QString::fromUtf8(RMAX) + "3\r\n";
            data = str_val.toLatin1();
            serail_send_start(data);
        } else if (i == 2) {
            // 设置MTH1默认为60  3.5米以内
            str_val = QString::fromUtf8(MTH1) + "88\r\n";
            data = str_val.toLatin1();
            serail_send_start(data);
        } else if (i == 3) {
            // 设置MTH2默认为55  3.5~10米以内
            str_val = QString::fromUtf8(MTH2) + "99\r\n";
            data = str_val.toLatin1();
            serail_send_start(data);
        } else if (i == 4) {
            // 设置MTH3默认为40  10米以外
            str_val = QString::fromUtf8(MTH3) + "119\r\n";
            data = str_val.toLatin1();
            serail_send_start(data);
        } else if (i == 5) {
            // 设置OUTPUT_MODE默认为1
            // 设置TONS默认为20
            // 设置UTONS默认为100
            // 保存设置
            str_val = QString::fromUtf8(GET_ALL_PARAMS) + "\r\n";
            data = str_val.toLatin1();
            serail_send_start(data);
        } else  {
            i = 0;
        }
        i++;
    }
}

void SerialOp::serail_send_start(QByteArray data)
{
    if (serail_ptr_) {
        serail_op_mtx_.lock();
        serail_ptr_->write(data);
        serail_op_mtx_.unlock();
    }
}

void SerialOp::setSerailPtr(QSerialPort *serail_ptr)
{
    serail_ptr_ = serail_ptr;
}

void SerialOp::openSerialPort(QString serail_str)
{
    qDebug() << "openSerialPort" << QThread::currentThread();
    // 绑定this线程创建对象
    serail_ptr_ = new QSerialPort(serail_str, this);
    // 打开串口
    DataSingleton *share_data = DataSingleton::GetInstace();
    qDebug("pthread runing");
    if (!serail_ptr_->open(QIODevice::ReadWrite)) {
        // 返回出错信号
        share_data->uart_port_status = false;
        emit onSerialPortOpenResult(false);
    } else {
        // 返回成功信号
        share_data->uart_port_status = true;
        // 使用 QMetaObject::invokeMethod 在主线程中更新 UI
        QMetaObject::invokeMethod(share_data->ui->seraiobt, "setEnabled", 
            Qt::QueuedConnection,
            Q_ARG(bool, false));
        QMetaObject::invokeMethod(share_data->ui->seraicbt, "setEnabled", 
            Qt::QueuedConnection,
            Q_ARG(bool, true));
        emit onSerialPortOpenResult(true);
    }
}

void SerialOp::setSerailParams(qint32 baudRate, QSerialPort::DataBits dataBits,\
                     QSerialPort::Parity parity, QSerialPort::StopBits stopbits,\
                     QSerialPort::FlowControl fc)
{
    qDebug() << "setSerailParams" << QThread::currentThread();
    if (serail_ptr_ != nullptr) {
        // 设置波特率
        serail_ptr_->setBaudRate(baudRate);
        // 设置数据位
        serail_ptr_->setDataBits(dataBits);
        // 设置校验位
        serail_ptr_->setParity(parity);
        // 设置停止位
        serail_ptr_->setStopBits(stopbits);
        // 设置流控
        serail_ptr_->setFlowControl(fc);
        // 监听串口的数据
        connect(serail_ptr_, &QSerialPort::readyRead, this, &SerialOp::recv_data);
    }
}

void SerialOp::closeSerialPort()
{
    if (serail_ptr_) {
        if (serail_ptr_->isOpen()) {
            qDebug() << "closeSerialPort" << QThread::currentThread();
            qDebug() << "close ---------------------";
            serail_ptr_->close();
        }
        delete serail_ptr_;
        serail_ptr_ = nullptr;
    }
}


